﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Workflow.Common.FileUtil;
using System.Configuration;
using Workflow.Common.Tools;
using Workflow.Dto;
using Workflow.IDAO;
using Workflow.IService;
using Workflow.Model;
using Workflow.Model.Enum;
using Workflow.Resource;
using System.Diagnostics;

namespace Workflow.Service
{
    public class ReceivedService : IReceivedService
    {
        public IWorkStatusDao WorkStatusDao { get; set; }
        public IFolerClassDao FolerClassDao { get; set; }
        public ICaseEEMDao CaseEEMDao { get; set; }


        private bool checkFileName(string fileName)
        {
            if (fileName.Length < 16)
            {
                Debug.WriteLine("file name length < 16");
                return false;
            }

            var re = "^[\\dm]{1}-\\d{8}-\\d{5}$";
            var reTwo = "^[\\dm]{1}-\\d{8}-\\d{5}-\\d{1}$";
            var date = fileName.Substring(2, 4) + "-" + fileName.Substring(6, 2) + "-" + fileName.Substring(8, 2);
            DateTime temp;
            if (System.Text.RegularExpressions.Regex.IsMatch(fileName, re))
            {
                if (DateTime.TryParse(date, out temp))
                {
                    return true;
                }
                Debug.WriteLine("file name match re successfull,but not a datetime.");
                return false;
            }
            if (System.Text.RegularExpressions.Regex.IsMatch(fileName, reTwo))
            {
                if (DateTime.TryParse(date, out temp))
                {
                    return true;
                }
                Debug.WriteLine("file name match reTwo successfull,but not a datetime.");
                return false;
            }
            return false;
        }

        /// <summary>
        /// 判断目录结构是否正确
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="batchNo"></param>
        /// <returns></returns>
        private bool CheckFilePath(string filePath, string batchNo, string caseType)
        {
            var tempPath = filePath.Split('\\');
            var arrFile = tempPath[tempPath.Length - 1].Split('.');

            if (arrFile[1] == "TIF" || arrFile[1] == "tif")
            {
                for (int i = 2; i < tempPath.Length; i++)
                {
                    var folderType = tempPath[tempPath.Length - i];
                    var parentType = tempPath[tempPath.Length - i - 1];

                    if (folderType == parentType)
                    {
                        return false;
                    }
                    if (folderType != batchNo && parentType != batchNo)
                    {
                        FolerClass folerClass = FolerClassDao.GetFolerClassByName(folderType, caseType);
                        if (folerClass == null)
                        {
                            return false;
                        }
                        if (folerClass.ParentCode == "0")
                        {
                            continue;
                        }
                        FolerClass parentClass = FolerClassDao.GetFolerClassByCode(folerClass.ParentCode);
                        if (parentClass.FolderNameEN != parentType)
                        {
                            return false;
                        }
                    }
                    else
                    {
                        return true;
                    }
                }
            }
            return true;
        }

        /// <summary>
        /// 忽略目录
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="ignoreCaseType">忽略的类型</param>
        /// <param name="ignoreType">是否忽略</param>
        /// <returns></returns>
        private bool IgnoreFile(string filePath, string ignoreCaseType, bool ignoreType, string belongCaseType)
        {
            var tempPath = filePath.Split('\\');
            var arrFile = tempPath[tempPath.Length - 1].Split('.');

            if (arrFile[1] == "TIF" || arrFile[1] == "tif")
            {
                var f_b = tempPath[tempPath.Length - 2];

                FolerClass belongfolerClass = FolerClassDao.GetFolerClassByName(f_b, belongCaseType);

                if (belongfolerClass == null)
                {
                    return true;
                }

                FolerClass ignorefolerClass = FolerClassDao.GetFolerClassByName(f_b, ignoreCaseType);

                if (ignorefolerClass != null && ignoreType)
                {
                    return true;
                }
            }
            return false;
        }
		
        #region EEM
        public IList<ReceivedFailDataDto> UpdateEEMReceivedCaseForFolder(string receiveDate)
        {
            var tifBasePath = ConfigurationManager.AppSettings["TifBasePath"];
            var path = tifBasePath + "\\" + receiveDate;

            List<ReceivedFailDataDto> receivedFailDataDtos = new List<ReceivedFailDataDto>();

            if (!Directory.Exists(path))
            {
                return receivedFailDataDtos;
            }
            var directorys = Directory.GetDirectories(path);

            foreach (var directory in directorys)
            {
                var folderAs = Directory.GetDirectories(directory);
                var batchNo = "";
                foreach (var folderA in folderAs)
                {
                    var tempPath = folderA.Split('\\');

                    var folderType = tempPath[tempPath.Length - 1];
                    batchNo = tempPath[tempPath.Length - 2];

                    FolerClass folerClass = FolerClassDao.GetFolerClassByName(folderType, ((int)EnumFolderClass.EEM).ToString());
                    //判断目录是否在DB中存在
                    if (folerClass == null)
                    {
                        FolerClass temp = FolerClassDao.GetFolerClassByName(folderType, ((int)EnumFolderClass.PTP).ToString());

                        if (temp != null)
                        {
                            continue;
                        }
                        ReceivedFailDataDto receivedFailDataDto = new ReceivedFailDataDto();
                        receivedFailDataDto.ReadFilePath = folderA;
                        receivedFailDataDto.ErrorMessage = Global.ReceivedFolderLevelError;
                        receivedFailDataDtos.Add(receivedFailDataDto);
                        continue;
                    }
                    //批次下一级目录是否是PTP或者EEM所属目录
                    if (folerClass.ParentCode != ((int)EnumFolderClass.PTP).ToString() && folerClass.ParentCode != ((int)EnumFolderClass.EEM).ToString())
                    {
                        ReceivedFailDataDto receivedFailDataDto = new ReceivedFailDataDto();
                        receivedFailDataDto.ReadFilePath = folderA;
                        receivedFailDataDto.ErrorMessage = Global.ReceivedFolderLevelError;
                        receivedFailDataDtos.Add(receivedFailDataDto);
                        continue;
                    }

                    if (folerClass.ParentCode == ((int)EnumFolderClass.EEM).ToString())
                    {

                        var fileList = FileUtil.GetAllFile(folderA);

                        IList<string> removePath = new List<string>();
                        foreach (var filePath in fileList)
                        {
                            if (!CheckFilePath(filePath, batchNo, ((int)EnumFolderClass.EEM).ToString()))
                            {
                                removePath.Add(filePath);
                                ReceivedFailDataDto receivedFailDataDto = new ReceivedFailDataDto();
                                receivedFailDataDto.ReadFilePath = filePath;
                                receivedFailDataDto.ErrorMessage = Global.ReceivedFolderLevelError;
                                receivedFailDataDtos.Add(receivedFailDataDto);
                            }
                        }
                        foreach (string temp in removePath)
                        {
                            fileList.Remove(temp);
                        }


                        receivedFailDataDtos.AddRange(CreatCaseEEM(fileList, receiveDate));
                    }
                }
            }

            return receivedFailDataDtos;
        }

        private IList<ReceivedFailDataDto> CreatCaseEEM(List<string> fileList, string receiveDate)
        {
            IList<ReceivedFailDataDto> receivedFailDataDtos = new List<ReceivedFailDataDto>();

            foreach (var file in fileList)
            {
                var data = file.Split('\\');

                var model = new CaseEEM();
                var arrFile = data[data.Length - 1].Split('.');
                if (arrFile[1] == "TIF" || arrFile[1] == "tif")
                {

                    if (!checkFileName(arrFile[0]))
                    {
                        ReceivedFailDataDto receivedFailDataDto = new ReceivedFailDataDto();

                        receivedFailDataDto.ErrorMessage = Global.ReceivedFileNameError;
                        receivedFailDataDto.ReadFilePath = file.Replace(ConfigurationManager.AppSettings["TifBasePath"], "");

                        receivedFailDataDtos.Add(receivedFailDataDto);
                        continue;
                    }
                    //后补图片不算
                    if (arrFile[0].Length > 16)
                    {
                        continue;
                    }
                    var temp = CaseEEMDao.GetGaseByFileName(arrFile[0].Substring(0, 16));
                    if (temp != null)
                    {
                        var readFilePath = file.Replace(ConfigurationManager.AppSettings["TifBasePath"], "");
                        var dbFilePath = temp.GetFolerPathEN() + temp.FileName + ".tif";
                        if (readFilePath.ToUpper() == dbFilePath.ToUpper())
                        {
                            continue;
                        }
                        ReceivedFailDataDto receivedFailDataDto = new ReceivedFailDataDto();

                        receivedFailDataDto.ErrorMessage = Global.ReceivedFileExistError;
                        receivedFailDataDto.ReadFilePath = readFilePath;
                        receivedFailDataDto.DBFilePath = dbFilePath;

                        receivedFailDataDtos.Add(receivedFailDataDto);
                        continue;
                    }


                    model.FileName = arrFile[0];
                    model.BatchNo = receiveDate + "-" + data[data.Length - 5];

                    var folderLevelA = FolerClassDao.GetFolerClassByName(data[data.Length - 4], ((int)EnumFolderClass.EEM).ToString());
                    if (folderLevelA == null)
                    {
                        ReceivedFailDataDto receivedFailDataDto = new ReceivedFailDataDto();

                        receivedFailDataDto.ErrorMessage = Global.ReceivedFolderLevelError;
                        receivedFailDataDto.ReadFilePath = file.Replace(ConfigurationManager.AppSettings["TifBasePath"], "");

                        receivedFailDataDtos.Add(receivedFailDataDto);

                        continue;
                    }
                    model.FolderLevelA = folderLevelA;
                    var folderLevelB = FolerClassDao.GetFolerClassByName(data[data.Length - 3], ((int)EnumFolderClass.EEM).ToString());
                    if (folderLevelB == null)
                    {

                        ReceivedFailDataDto receivedFailDataDto = new ReceivedFailDataDto();

                        receivedFailDataDto.ErrorMessage = Global.ReceivedFolderLevelError;
                        receivedFailDataDto.ReadFilePath = file.Replace(ConfigurationManager.AppSettings["TifBasePath"], "");

                        receivedFailDataDtos.Add(receivedFailDataDto);

                        continue;
                    }
                    model.FolderLevelB = folderLevelB;
                    var checkType = FolerClassDao.GetFolerClassByName(data[data.Length - 2], ((int)EnumFolderClass.EEM).ToString());
                    if (checkType == null)
                    {
                        ReceivedFailDataDto receivedFailDataDto = new ReceivedFailDataDto();

                        receivedFailDataDto.ErrorMessage = Global.ReceivedFolderLevelError;
                        receivedFailDataDto.ReadFilePath = file.Replace(ConfigurationManager.AppSettings["TifBasePath"], "");

                        receivedFailDataDtos.Add(receivedFailDataDto);

                        continue;
                    }
                    model.CheckType = checkType;
                    model.WorkStatus = WorkStatusDao.Get(((int)EnumWorkStatus.Received).ToString());
                    model.StatusDate = ToolsHelper.GetTimeZoneNow();
                    model.ReceiveDate = ToolsHelper.GetTimeZoneNow();
                    CaseEEMDao.Save(model);
                }
            }
            return receivedFailDataDtos;
        }
        #endregion

    }
}
